package com.eqdd.yiqidian.ui;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.eqdd.annotation.datasave.DealCodeClass;
import com.eqdd.floatingmenu.MenuItem;
import com.eqdd.floatingmenu.TopRightMenu;
import com.eqdd.yiqidian.MainActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.base.CodeRule;
import com.eqdd.yiqidian.bean.LoginRecordBean;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.fragment.FaxianFragment;
import com.eqdd.yiqidian.fragment.FunctionFragment;
import com.eqdd.yiqidian.fragment.MineFragment;
import com.eqdd.yiqidian.fragment.TongxunluFragment;
import com.eqdd.yiqidian.fragment.XiaoxiFragment;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.kotlin.net.HttpResult;
import com.eqdd.yiqidian.rxbus2.Subscribe;
import com.eqdd.yiqidian.rxbus2.ThreadMode;
import com.eqdd.yiqidian.share.JShareDialog;
import com.eqdd.yiqidian.share.TextShareBuilder;
import com.eqdd.yiqidian.ui.function.learn.GoLearnMainActivity;
import com.eqdd.yiqidian.ui.function.shopping.GoShoppingMainActivity;
import com.eqdd.yiqidian.ui.mine.setting.FeedbackActivity;
import com.eqdd.yiqidian.ui.tongxunlu.AddFriendFirstTypeActivity;
import com.eqdd.yiqidian.ui.yiqiyue.YueMainActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.PreferenceUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.gamerole.floatactionmenulib.RapidFloatingActionHelper;
import com.gamerole.floatactionmenulib.contentimpl.labellist.RFACLabelItem;
import com.gamerole.floatactionmenulib.contentimpl.labellist.RapidFloatingActionContentLabelList;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.roughike.bottombar.BottomBarTab;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import me.leolin.shortcutbadger.ShortcutBadger;

public class MainActivity extends BaseActivity implements RongIM.UserInfoProvider, IUnReadMessageObserver
        , RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener {


    private SparseArray<Class> menuArray = new SparseArray();
    private static final int REQUEST_CODE = 1;
    private MainActivityCustom dataBinding;
    private User user;
    private String fragment1Tag = "消息";
    private String fragment2Tag = "通讯录";
    private String fragment3Tag = "功能";
    private String fragment4Tag = "发现";
    private String fragment5Tag = "我的";
    private BottomBarTab xiaoxi;
    private BottomBarTab tongxunlu;
    private BottomBarTab faxian;
    private BottomBarTab mine;
    private BottomBarTab function;
    private RapidFloatingActionHelper rfabHelper;

    @DealCodeClass(classes = {TongxunluFragment.class})
    public void updateFriendApplyNum(int num) {
        if (num > 0) {
            tongxunlu.setBadgeCount(num);
        } else {
            tongxunlu.removeBadge();
        }
    }

    @DealCodeClass(classes = {MineFragment.class})
    public void updateMineNum(int num) {
        if (num > 0) {
            mine.setBadgeCount(num);
        } else {
            mine.removeBadge();
        }
    }

    @DealCodeClass(classes = {FaxianFragment.class})
    public void updateFaxian(int num) {
        if (num > 0) {
            faxian.setBadgeCount(num);
        } else {
            faxian.removeBadge();
        }
    }

    @DealCodeClass(classes = {FunctionFragment.class})
    public void updateGongneng(int num) {
        if (num > 0) {
            function.setBadgeCount(num);
        } else {
            function.removeBadge();
        }
    }

    @Subscribe(code = CodeRule.USER_INFO, threadMode = ThreadMode.MAIN)
    public void updateUser() {
        user = GreenDaoUtil.getUser();
    }


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        //初始化一个雪花样式的fallObject
//        FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.mipmap.ic_cloud));
//        FallObject fallObject = builder
//                .setSpeed(3, true)
//                .setSize(50, 50, true)
//                .setWind(5, true, true)
//                .build();
//        dataBinding.fallView.addFallObject(fallObject, 100);//添加50个下落物体对象
    }

    @Override
    public void initData() {
        isDealCode = true;
        isRxbus = true;
        user = GreenDaoUtil.getUser();
        menuArray.put(0, GoLearnMainActivity.class);
        menuArray.put(1, YueMainActivity.class);
        // menuArray.put(1, CreateSpaceActivity.class);
        menuArray.put(2, GoShoppingMainActivity.class);
        initRong();
        initBottomBar();
        initSlideUpMenu();
    }

    private void initSlideUpMenu() {
        RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(this);
        rfaContent.setOnRapidFloatingActionContentLabelListListener(this);
        List<RFACLabelItem> items = new ArrayList<>();
        items.add(new RFACLabelItem<Integer>()
                .setLabel("易企学")
                .setResId(R.mipmap.xue)
                .setIconNormalColor(0xff056f00)
                .setIconPressedColor(0xff0d5302)
                .setLabelColor(0xff056f00)
                .setWrapper(0)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("易企阅")
                .setResId(R.mipmap.yue)
                .setIconNormalColor(0xffd84315)
                .setIconPressedColor(0xffbf360c)
                .setLabelColor(0xff056f00)
                .setWrapper(1)
        );
        //todo 暂时关闭
       /* items.add(new RFACLabelItem<Integer>()
                .setLabel("易企创")
                .setResId(R.mipmap.chuang)
                .setIconNormalColor(0xff4e342e)
                .setIconPressedColor(0xff3e2723)
                .setLabelColor(0xff056f00)
                .setLabelSizeSp(14)
                .setWrapper(1)
        );*/

        items.add(new RFACLabelItem<Integer>()
                .setLabel("易企购")
                .setResId(R.mipmap.gou)
                .setIconNormalColor(0xff00c1ff)
                .setIconPressedColor(0xff2aaeee)
                .setLabelColor(0xff056f00)
                .setWrapper(2)
        );
        rfaContent
                .setItems(items);
//                .setIconShadowRadius(ABTextUtil.dip2px(this, 0))
//                .setIconShadowColor(0xff888888)
//
//                .setIconShadowDy(ABTextUtil.dip2px(this, 0));
        dataBinding.activityMainRfal.setLabelVisibility(false);
        rfabHelper = new RapidFloatingActionHelper(
                this,
                dataBinding.activityMainRfal,
                dataBinding.activityMainRfab,
                rfaContent
        ).build();
    }

    @Override
    public void onRFACItemLabelClick(int position, RFACLabelItem item) {
        rfabHelper.toggleContent();
        dealMenu(position);
    }

    private void dealMenu(int position) {
        if (menuArray.get(position) != null) {
            startActivity(menuArray.get(position));
        }
    }

    @Override
    public void onRFACItemIconClick(int position, RFACLabelItem item) {
        rfabHelper.toggleContent();
        dealMenu(position);
    }

    @Override
    public void setView() {
        RxView.clicks(dataBinding.includeTitle.ivSearch)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> startActivity(SearchActivity.class));


    }

    @Override
    public void lastRun() {
        if (register != null) {
            ((MainActivity$$DealCodeInjector) register).update1();
            ((MainActivity$$DealCodeInjector) register).update2();
            ((MainActivity$$DealCodeInjector) register).update3();
            ((MainActivity$$DealCodeInjector) register).update4();
        }
    }

    private void initBottomBar() {
        mine = dataBinding.bottomBar.getTabWithId(R.id.tab_my);
        xiaoxi = dataBinding.bottomBar.getTabWithId(R.id.tab_xiaoxi);
        tongxunlu = dataBinding.bottomBar.getTabWithId(R.id.tab_tongxunlu);
        faxian = dataBinding.bottomBar.getTabWithId(R.id.tab_faxian);
        function = dataBinding.bottomBar.getTabWithId(R.id.tab_function);
        dataBinding.bottomBar.setDefaultTab(R.id.tab_function);
        dataBinding.bottomBar.setOnTabSelectListener(this::onChecked);
    }

    public void onChecked(int checkedId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment fragment1 = fm.findFragmentByTag(fragment1Tag);
        Fragment fragment2 = fm.findFragmentByTag(fragment2Tag);
        Fragment fragment3 = fm.findFragmentByTag(fragment3Tag);
        Fragment fragment4 = fm.findFragmentByTag(fragment4Tag);
        Fragment fragment5 = fm.findFragmentByTag(fragment5Tag);
        if (fragment1 != null) {
            ft.hide(fragment1);
        }
        if (fragment2 != null) {
            ft.hide(fragment2);
        }
        if (fragment3 != null) {
            ft.hide(fragment3);
        }
        if (fragment4 != null) {
            ft.hide(fragment4);
        }
        if (fragment5 != null) {
            ft.hide(fragment5);
        }
        switch (checkedId) {
            case R.id.tab_xiaoxi:
                if (fragment1 == null) {
                    fragment1 = new XiaoxiFragment();
                    ft.add(R.id.contentContainer, fragment1, fragment1Tag);
                } else {
                    ft.show(fragment1);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("消息");
                findViewById(R.id.iv_search).setVisibility(View.VISIBLE);
                dataBinding.activityMainRfab.setVisibility(View.GONE);
                break;
            case R.id.tab_tongxunlu:
                if (fragment2 == null) {
                    fragment2 = new TongxunluFragment();
                    ft.add(R.id.contentContainer, fragment2, fragment2Tag);
                } else {
                    ft.show(fragment2);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("通讯录");
                findViewById(R.id.iv_search).setVisibility(View.GONE);
                dataBinding.activityMainRfab.setVisibility(View.GONE);

                break;
            case R.id.tab_function:
                if (fragment3 == null) {
                    fragment3 = new FunctionFragment();
                    ft.add(R.id.contentContainer, fragment3, fragment3Tag);
                } else {
                    ft.show(fragment3);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("易企点工业互联网平台");
                findViewById(R.id.iv_search).setVisibility(View.GONE);
                dataBinding.activityMainRfab.setVisibility(View.VISIBLE);


                break;
            case R.id.tab_faxian:
                if (fragment4 == null) {
                    fragment4 = new FaxianFragment();
                    ft.add(R.id.contentContainer, fragment4, fragment4Tag);
                } else {
                    ft.show(fragment4);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("发现");
                findViewById(R.id.iv_search).setVisibility(View.GONE);

                dataBinding.activityMainRfab.setVisibility(View.GONE);

                break;
            case R.id.tab_my:
                if (fragment5 == null) {
                    fragment5 = new MineFragment();
                    ft.add(R.id.contentContainer, fragment5, fragment5Tag);
                } else {
                    ft.show(fragment5);
                }
                ((TextView) findViewById(R.id.tv_title)).setText("我的");
                findViewById(R.id.iv_search).setVisibility(View.GONE);
                dataBinding.activityMainRfab.setVisibility(View.GONE);

                break;
            default:
                break;
        }
        ft.commit();
    }

    private void initRong() {
        RongIM.setUserInfoProvider(this, true);
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };
        RongIM.getInstance().setMessageAttachedUserInfo(true);

        /**
         * 刷新用户缓存数据。
         *
         * @param userInfo 需要更新的用户缓存数据。
         */
        RongIM.getInstance().setCurrentUserInfo(new UserInfo(user.getGuid(), user.getPname(), Uri.parse(user.getIphoto())));
        RongIM.getInstance().refreshUserInfoCache(new UserInfo(user.getGuid(), user.getPname(), Uri.parse(user.getIphoto())));
        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);
    }


    private void initChooseDialog(View v) {
        List<MenuItem> menuItems = new ArrayList<>();
        menuItems.add(new MenuItem("扫一扫"));
        menuItems.add(new MenuItem("加好友"));
        menuItems.add(new MenuItem("邀请好友注册"));
        menuItems.add(new MenuItem("帮助与反馈"));

        TopRightMenu mTopRightMenu = new TopRightMenu(this);
        mTopRightMenu
                .setHeight(380)     //默认高度480
                .setWidth(300)      //默认宽度wrap_content
                .showIcon(false)     //显示菜单图标，默认为true
                .dimBackground(true)        //背景变暗，默认为true
                .needAnimationStyle(true)   //显示动画，默认为true
                .setAnimationStyle(R.style.TRM_ANIM_STYLE)
                .addMenuList(menuItems)
                .top(TopRightMenu.Align.RIGHT, 10, 30)
                .setOnMenuItemClickListener(position -> {
                    switch (position) {
                        case 0:
                            RxPermissions.getInstance(this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe(granted -> {
                                        // 当R.id.enableCamera被点击的时候触发获取权限
                                        if (granted) {
                                            Intent intent = new Intent(MainActivity.this, ScanZXingActivity.class);
                                            startActivityForResult(intent, REQUEST_CODE);
                                        } else {
                                            ToastUtil.showLong("请在设置中开启照相权限");
                                        }
                                    });
                            break;
                        case 1:
                            RxPermissions.getInstance(MainActivity.this).request(android.Manifest.permission.READ_CONTACTS)
                                    .subscribe(granted -> {
                                        if (!granted) {
                                            ToastUtil.showShort("请允许应用获取联系人信息");
                                            Intent intent = new Intent();
                                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                                            intent.setData(uri);
                                            startActivity(intent);
                                        } else {
                                            startActivity(AddFriendFirstTypeActivity.class);
                                        }
                                    });
                            break;
                        case 2:
                            String s = TextUtils.isEmpty(AppConstent.user.getUsername()) ? "" : "(" + AppConstent.user.getUsername() + ")";
                            TextShareBuilder builder = new TextShareBuilder(this);
                            builder.setTitle("易企点")
                                    .setText("【易企点】您的朋友:" + user.getUname() + s + "邀请您注册易企点,点击 https://www.eqidd.com/html/adjust.html 注册")
                                    .setSource("易企点")
                                    .build();

                            new JShareDialog(builder, this).show();
                            break;
                        case 3:
                            Intent intent = new Intent(this, FeedbackActivity.class);
                            startActivity(intent);

                            break;
                    }
                }).showAsDropDown(v, 8, 0);    //带偏移量;
    }

    @Override
    public UserInfo getUserInfo(String s) {
        return new UserInfo(user.getGuid(), user.getPname(),
                Uri.parse(user.getIphoto()));//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
    }

    @Override
    public void onCountChanged(int i) {
//        startService(new Intent(MainActivity.this, RongyunService.class));
        System.out.println("未读消息树" + i);
        if (i <= 0) {
            xiaoxi.removeBadge();
            ShortcutBadger.removeCount(BaseApplication.getApplication());
        } else {
            xiaoxi.setBadgeCount(i);
            ShortcutBadger.applyCount(BaseApplication.getApplication(), i);

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add:
                initChooseDialog(v);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
        super.onDestroy();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exit();
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        LoginRecordBean bean = PreferenceUtil.find(BaseApplication.context, AppConstent.LOGIN_RECORD, LoginRecordBean.class);
        if (bean != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
            String str = sdf.format(new Date());
            OkGo.<HttpResult<Integer>>post(HttpConfig.BASE_URL + HttpConfig.RECORD_EXIT)
                    .params("userGuid", user.getGuid())
                    .params("logId", bean.getLoginId())
                    .params("time", str)
                    .execute(new JsonCallBack<HttpResult<Integer>>() {
                        @Override
                        public void onSuccess(Response<HttpResult<Integer>> response) {
                            HttpResult<Integer> result = response.body();
                            if (result.getStatus() == 200) {
                                PreferenceUtil.delete(BaseApplication.context, AppConstent.LOGIN_RECORD, LoginRecordBean.class);
                            }
                        }
                    });
        }

    }

}
